package com.nintendo.filter;

import jakarta.servlet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;

@Component
public class LogFilter implements Filter {
    private Logger log = LoggerFactory.getLogger(LogFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        String remoteAddr = request.getRemoteAddr(); // 远程地址
        String serverName = request.getServerName(); // 请求方式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        long end = System.currentTimeMillis();
        log.info("远程地址：{}，请求地址：{}，请求时间：{}，请求耗时：{}ms", remoteAddr, serverName, simpleDateFormat.format(start), end - start);
       filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
